package com.navcoo.yidaaddproapi.service.serviceImpl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.navcoo.yidaaddproapi.constants.RedisKeyConstants;
import com.navcoo.yidaaddproapi.service.UpdateMessageService;
import com.navcoo.yidaaddproapi.utils.HttpUtil;
import com.navcoo.yidaaddproapi.utils.RedisUtil;
import com.taobao.api.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * 更新消息服务Impl
 *
 * @author Navcoo
 * @date 2024-05-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UpdateMessageServiceImpl implements UpdateMessageService {

    private final RedisUtil redisUtil;

    @Override
    public void updateMessage() {
        JSONObject updateDataJson = searchYidaUpdates();
        if (redisUtil.hasKey(RedisKeyConstants.YIDA_UPDATE_MESSAGE)) {
            if (StrUtil.equals(JSONUtil.parseObj(redisUtil.get(RedisKeyConstants.YIDA_UPDATE_MESSAGE)).getStr("slug"), updateDataJson.getStr("slug"))) {
                log.info("缓存数据与当前最新数据一致");
                return;
            } else {
                redisUtil.del(RedisKeyConstants.YIDA_UPDATE_MESSAGE);
                redisUtil.set(RedisKeyConstants.YIDA_UPDATE_MESSAGE, JSONUtil.toJsonStr(updateDataJson), -1);
                log.info("更新消息成功");
                customRobotGroupMessage(updateDataJson);
            }
        }
        redisUtil.set(RedisKeyConstants.YIDA_UPDATE_MESSAGE, JSONUtil.toJsonStr(updateDataJson), -1);
        log.info("更新消息成功");
        customRobotGroupMessage(updateDataJson);
    }

    public JSONObject searchYidaUpdates() {
        String result = HttpUtil.doGet("https://www.yuque.com/api/docs?book_id=11032369");
        JSONObject resultJson = new JSONObject(result);
        JSONObject updateDataJson = JSONUtil.createObj()
                .set("slug", resultJson.getJSONArray("data").getJSONObject(0).getStr("slug"))
                .set("title", resultJson.getJSONArray("data").getJSONObject(0).getStr("title"));
        log.info(updateDataJson.toString());
        return updateDataJson;
    }


    public void customRobotGroupMessage(JSONObject updateDataJson) {
        String CUSTOM_ROBOT_TOKEN = "fa01780cd30433f779ca82c43976a0a6110dc9b659fd2a6bce4671d758aab219";
        String SECRET = "SECb1cc5bc4e703554f99e9cab0d4508b47d90b56ee24eacb72a5a47456b61df54b";
        try {
            Long timestamp = System.currentTimeMillis();
            System.out.println(timestamp);
            String stringToSign = timestamp + "\n" + SECRET;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8);
            System.out.println(sign);

            //sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);

            OapiRobotSendRequest req = new OapiRobotSendRequest();

            OapiRobotSendRequest.Btns btns = new OapiRobotSendRequest.Btns();
            btns.setTitle("点击查看更新内容");
            btns.setActionURL("https://www.yuque.com/yida/updates/" + updateDataJson.getStr("slug"));

            List<OapiRobotSendRequest.Btns> btnsLsit = new ArrayList<>();
            btnsLsit.add(btns);
            OapiRobotSendRequest.Actioncard actioncard = new OapiRobotSendRequest.Actioncard();
            actioncard.setTitle("宜搭更新提醒");
            actioncard.setText("#### 宜搭平台更新，请及时关注\n[[" + updateDataJson.getStr("slug") + "](https://www.yuque.com/yida/updates/" + updateDataJson.getStr("slug") + ")] " + updateDataJson.getStr("title"));
            actioncard.setBtns(btnsLsit);
            actioncard.setBtnOrientation("0");

            req.setMsgtype("actionCard");
            req.setActionCard(actioncard);

            OapiRobotSendResponse rsp = client.execute(req, CUSTOM_ROBOT_TOKEN);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }


}
